var Visit = require('../model/visit.js');
var request = require('request');

exports.index = function(req,res,next){
    var ip = req.headers['x-forwarded-for'];
    if(ip){
        ip = ip.split(',');
        ip = ip[0];
        console.log(ip);
        if(ip){
            //ip = "124.200.183.90";
            var url = "https://dm-81.data.aliyun.com/rest/160601/ip/getIpInfo.json?ip=" + ip;


            request({
                url: url,
                rejectUnauthorized: false,
                headers: {
                    "Authorization": "APPCODE 0c21f9ba9e8d48128729b9b501a9a5e7"
                }
            },function(err,response,body) {

                console.log(err);
                console.log(body);
                body = JSON.parse(body);
                if (body && body.code == 0) {
                    console.log("get result");
                    var visit = new Visit({
                         ip:ip,
                         info:body.data
                     });
                     visit.save(function(err,result){
                         console.log(err);
                         console.log(result);
                     });
                }
            });
        }

    }

    res.render('index', { title: 'yewenwen' });
}

exports.manager = function(req,res,next){
    Visit.find({},function(err,data){
        if(err){
            console.log(err);
            res.send(err);
        } else {
            res.send(data);
        }
    });
}